const path = require('path')
const fs = require('fs')

const fromFile = path.resolve(__dirname, '../../pages.json')
const toFile = path.resolve(__dirname, './router.js')
const toFile2 = path.resolve(__dirname, './routerAll.js')

function createRouter() {
	const buffPrefix = Buffer.from('export default ')
	const fileData = fs.readFileSync(fromFile)
	// 转成可读的js, 正则删除注释， 不然JSON.parse会报错
	const fileObj = JSON.parse(fileData.toString().replace(/\/\/.*/g, ''))
	// 遍历，只取路径和标题，其他的不要，已减小文件体积
	const routes = fileObj.tabBar
	const routes2 = []
	// // 如果有分包
	if (fileObj.subPackages) {
		fileObj.subPackages.forEach(e => {
			e.pages.forEach(i => {
				routes2.push({
					title: i.style ? i.style.navigationBarTitleText : '未知',
					path: '/' + e.root + '/' + i.path,
				})
			})
		})
	}
	fileObj.pages.forEach(i => {
		routes2.push({
			title: i.style ? i.style.navigationBarTitleText : '未知',
			path: '/' + i.path,
		})
	})

	// // 如果router目录不存在就创建目录
	// if (!fs.existsSync(toFile)) {
	// fs.mkdirSync(path.resolve(__dirname, './router'))
	// }
	fs.writeFileSync(toFile, buffPrefix + Buffer.from(JSON.stringify(routes)))
	//routes2 分包+pages
	fs.writeFileSync(toFile2, buffPrefix + Buffer.from(JSON.stringify(routes2)))
}

// 监听pages.json改动
if (process.env.NODE_ENV !== 'production') {
	fs.watchFile(fromFile, () => {
		createRouter()
		console.log('路由文件更新')
	})
}
createRouter()